package com.zhihuitong.meeting.meeting.list;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huawei.cloudlink.openapi.api.CLMCompleteHandler;
import com.huawei.cloudlink.openapi.api.CLMNotifyHandler;
import com.huawei.cloudlink.openapi.api.CLMResult;
import com.huawei.cloudlink.openapi.api.CloudLinkSDK;
import com.huawei.cloudlink.openapi.api.OpenApiConst;
import com.zhihuitong.meeting.R;
import com.zhihuitong.meeting.base.BaseActivity;
import com.zhihuitong.meeting.global.HuaWeiUserProvider;
import com.zhihuitong.meeting.global.MyApplication;
import com.zhihuitong.meeting.meeting.create.CreatMeetingActivity;
import com.zhihuitong.meeting.utils.ActivityUtils;
import com.zhihuitong.meeting.utils.ToastUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者：guoyuan
 * 时间: 2020/2/22.
 * 文件描述：应用程序入口
 * 版本号：V 1.0
 **/
public class MainActivity extends BaseActivity {


    @BindView(R.id.fl_content)
    FrameLayout mFlContent;
    @BindView(R.id.btn_creatMeeting)
    Button mBtnCreatMeeting;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tv_release)
    TextView mTvRelease;


    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }


    /**
     * 返回子类布局id
     *
     * @return
     */
    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    /**
     * 初始化數據
     */
    @Override
    protected void initData() {
        showLoading();
        ToastUtils.showToast("应用程序初始化中...请稍后!");
        CloudLinkSDK.getOpenApi().clmInit(getApplication(), mContext, "openSDKDemo", new CLMCompleteHandler() {
            @Override
            public void onCompleted(CLMResult result) {
                String msg = "code =" + result.getCode() + "Message=" + result.getMessage() + "Data=" + result.getData() + "Cmd=" + result.getCmd();
                Log.i("huawei", msg);
                if (result.getCode() == 0) {
                    if (MyApplication.isClmInit) {
                        hidLoading();
                        //退出视频会议,释放账号
                       // releaseHuaWeiUser(false);
                        return;
                    }
                    ToastUtils.showToast("应用程序初始化成功!");
                    MyApplication.isClmInit = true;
                    hidLoading();
                } else {
                    hidLoading();
                    ToastUtils.showToast("初始化失败!");
                }
            }
        }, notifyHandler, null);
    }

    public CLMNotifyHandler notifyHandler = new CLMNotifyHandler() {
        @Override
        public void clmUserWasKickedOut(CLMResult result) {
            Log.i("huawei", result.toString());
            // 账号被T，需要重新登录
            AlertDialog.Builder builder = new AlertDialog.Builder(ActivityUtils.getTopActivity());
            builder.setMessage("您的账号已经在其他设备登录");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.create().show();
        }
    };

    /**
     * 初始化View
     */
    @Override
    protected void initView() {
        mToolbar.setTitle("智会通视频会议");
        Log.i("===", "MainActivity");
        MeetingListFragment fragment = (MeetingListFragment) getSupportFragmentManager().findFragmentById(R.id.fl_content);
        if (fragment == null) {
            fragment = MeetingListFragment.getInstance();
            getSupportFragmentManager().beginTransaction().add(R.id.fl_content, fragment).commit();
        }
    }


    /**
     * 创建会议
     */
    private void creatMeeting() {
        CreatMeetingActivity.start(mContext);
    }


    @OnClick({R.id.tv_release, R.id.btn_creatMeeting, R.id.btn_joinMeeting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_release:
                releaseHuaWeiUser(false);
                break;
            case R.id.btn_creatMeeting:
                creatMeeting();
                break;
            case R.id.btn_joinMeeting:
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                View diglogView = View.inflate(mContext, R.layout.dialog_join_meeting_view, null);
                final AlertDialog alertDialog = builder.setView(diglogView).create();
                final EditText meeting_id = diglogView.findViewById(R.id.meeting_id);
                final EditText meeting_pass = diglogView.findViewById(R.id.meeting_pass);
                Button join_btn = diglogView.findViewById(R.id.join_btn);
                join_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String meetingId = meeting_id.getText().toString().trim();
                        String meetingPass = meeting_pass.getText().toString().trim();
                        if (TextUtils.isEmpty(meetingId)) {
                            ToastUtils.showToast("会议id不能为空!");
                            return;
                        }
                        if (TextUtils.isEmpty(meetingPass)) {
                            ToastUtils.showToast("入会密码不能为空!");
                            return;
                        }

                        alertDialog.dismiss();
                        //获取账号并登陆
                        showLoading();
                       // getHuaweiUser(meetingId, meetingPass, MyApplication.getLocalUserName());
                        //进入会议
                         joinMeeting(meetingId, meetingPass,  MyApplication.getLocalUserName());
                    }
                });
                alertDialog.show();
                break;
        }
    }


    /**
     * 手动入会
     *
     * @param meetingId
     * @param meetingPass
     * @param meetingNickname
     */
    private void joinMeeting(String meetingId, String meetingPass, String meetingNickname) {
        //使用来宾密码入会
        CloudLinkSDK.getOpenApi().clmJoinMeetingById(meetingId, meetingPass, meetingNickname, new CLMCompleteHandler() {
            @Override
            public void onCompleted(CLMResult result) {
                hidLoading();
                if (result.getCmd().equals(OpenApiConst.OPEN_EVENT_JOIN_MEETING_BY_ID)) {
                    Log.i("huawei", "join meeting result" + result.getMessage());
                    if (result.getCode() != 0) {
//                        Intent intent = new Intent(mContext, MainActivity.class);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        startActivity(intent);
                        ToastUtils.showToast(result.getMessage());
                        Log.e("huawei", "join meeting fail" + result.getMessage());
                    }
                }
            }
        });
    }

    /**
     * 获取华为账号
     *
     * @param meetingId
     * @param meetingPass
     * @param meetingNickname
     */
    private void getHuaweiUser(final String meetingId, final String meetingPass, final String meetingNickname) {
        HuaWeiUserProvider.getUser(MyApplication.getLocalAccount(), MyApplication.getLocalPwd(), new HuaWeiUserProvider.onHuaWeiUserListener() {
            @Override
            public void onHuaWeiUserSuccess(String userId, String pwd) {
                HuaWeiUserProvider.huaWeiLogin(userId, pwd, new CLMCompleteHandler() {
                    @Override
                    public void onCompleted(CLMResult result) {
                        if (result.getCode() == 0) {
                            ToastUtils.showToast("账号登录成功");
                            //加入会议
                            joinMeeting(meetingId, meetingPass, meetingNickname);
                        } else {
                            hidLoading();
                            Log.e("huawei", "login fail" + result.getMessage());
                            ToastUtils.showToast("账号登录失败" + "\nlogin fail" + result.getMessage());
                        }
                    }
                });
            }

            @Override
            public void onHuaWeiUserFail(String msg) {
                hidLoading();
                ToastUtils.showToast(msg);
            }
        });
    }

    /**
     * 释放华为云账号
     *
     * @param isExit
     */
    private void releaseHuaWeiUser(final boolean isExit) {

        showLoading();
        HuaWeiUserProvider.releaseHuaWeiUser(MyApplication.getLocalAccount(), MyApplication.getLocalPwd(), new HuaWeiUserProvider.onHuaWeiUserListener() {
            @Override
            public void onHuaWeiUserSuccess(String userId, String pwd) {
                hidLoading();
                if (isExit) {
                    ToastUtils.showToast("账号已释放,正常退出!");
                    finish();
                    System.exit(0);
                } else {
                    ToastUtils.showToast("当前账号释放成功!");

                }
            }

            @Override
            public void onHuaWeiUserFail(String msg) {
                hidLoading();
                if (isExit) {
                    ToastUtils.showToast("账号未释放,请联系管理员");
                    finish();
                    System.exit(0);
                } else {
                    ToastUtils.showToast(msg);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("===", MainActivity.class.getName() + "onDestroy");
    }


    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                releaseHuaWeiUser(true);

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
